package com.wwc.bwcj.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.wwc.bwcj.R
import com.wwc.bwcj.entity.CartProduct
import com.wwc.bwcj.entity.Product
import com.wwc.bwcj.util.CartManager
import com.wwc.bwcj.util.SelectSpecDialog

/**
 * 在点单页面展示商品列表，并处理用户选择商品规格和添加到购物车的操作
 */
class ProductAdapter(private val products: List<Product>) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

    // 内部可变列表，用于动态更新数据
    private val mutableProducts = products.toMutableList()

    // 创建 ProductViewHolder 实例, 加载 item_product 布局文件
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_product, parent, false)
        return ProductViewHolder(view, mutableProducts)  // 传递可变列表
    }

    // 将指定位置的商品数据绑定到 ViewHolder
    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val product = mutableProducts[position]
        holder.bind(product)
    }

    // 返回商品列表大小
    override fun getItemCount(): Int = mutableProducts.size

    //清空现有数据并添加新数据
    //更新商品列表数据
    //调用 notifyDataSetChanged() 刷新界面
    fun submitList(list: List<Product>) {
        mutableProducts.clear()
        mutableProducts.addAll(list)
        notifyDataSetChanged()
    }

    class ProductViewHolder(itemView: View, private val products: List<Product>) : RecyclerView.ViewHolder(itemView) {
        private val productName: TextView = itemView.findViewById(R.id.product_name)
        private val productDescription: TextView = itemView.findViewById(R.id.product_description)
        private val productPrice: TextView = itemView.findViewById(R.id.product_price)
        private val productImage: ImageView = itemView.findViewById(R.id.product_image)
        private val selectSpecButton: Button = itemView.findViewById(R.id.select_spec_button)

        fun bind(product: Product) {
            productName.text = product.name
            productDescription.text = product.description
            productPrice.text = product.price
            productImage.setImageResource(product.imageRes)

            // 调用SelectSpecDialog里的回调函数，得到用户选择的规格数据
            selectSpecButton.setOnClickListener {
                val dialog = SelectSpecDialog(itemView.context)
                dialog.onConfirmListener = { size, ice, sugar ->
                    addToCart(product.name,product.price, size, ice, sugar)
                }
                dialog.show()
            }
        }

        // 添加购物车商品对象，数据来源于SelectSpecDialog里的回调函数中用户选择的规格数据
        fun addToCart(name: String,price: String, size: String, ice: String, sugar: String) {
            // 根据商品名称查找对应商品
            val product = products.find { it.name == name }
            if (product != null) {
                // 提取数值部分并转换为 Double
                val priceValue = extractPriceValue(price)
                // 创建新商品，这里使用的是 CartProduct 类，区别与点单页面中的Product 类
                val cartProduct = CartProduct(
                    productId = name.hashCode().toString(),
                    productName = name,
                    imageUrl = "",
                    price = priceValue,
                    size = size,
                    ice = ice,
                    sugar = sugar,
                    quantity = 1
                )

                // 添加到购物车
                CartManager.addProduct(cartProduct)

                // 提示用户已添加
                Log.d("OrderFragment", "已添加至购物车: $name, 规格: $size, 冰量: $ice, 糖量: $sugar")
            } else {
                Log.e("OrderFragment", "未找到商品: $name")
            }
        }
        // 提取价格字符串中的数值部分
        private fun extractPriceValue(priceString: String): Double {
            // 使用正则表达式提取数字部分（包括小数）
            val regex = Regex("[0-9]+(\\.[0-9]+)?")
            val matchResult = regex.find(priceString)
            return matchResult?.value?.toDoubleOrNull() ?: 0.0
        }
    }
}

